package com.hzm.test;

import com.google.gson.Gson;
import com.hzm.test.model.Club;
import com.hzm.test.model.Config;
import com.hzm.test.service.ClubService;
import com.hzm.test.service.ConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.cache.concurrent.ConcurrentMapCacheManager;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class HelloController {

    @Autowired
    private ClubService clubService;

    @Autowired
    private ConfigService configService;

    @Autowired
    private ConcurrentMapCacheManager concurrentMapCacheManager;

    @Autowired
    private RedisCacheManager redisCacheManager;

    @GetMapping(value = "/redis_cache_test")
    public String redis_cache_test(@RequestParam(name = "key") String key,
                                   @RequestParam(name = "update", required = false) Boolean update) {

        if (update == null) {
            update = Math.random() > 0.5;
        }

        System.out.println("== redis_cache_test controller: " + key + " -- update: " + update);

        List<Club> clubList = null;
        if (update) {
            clubList = clubService.listRankCacheUpdate(key);
        } else {
            clubList = clubService.listRankByCache(key);
        }
        System.out.println(" ");

        return new Gson().toJson(clubList) + "<br/><br/><br/>";
    }


    @GetMapping(value = "/jvm_cache_test")
    public String jvm_cache_test(@RequestParam(name = "key") String key,
                                 @RequestParam(name = "update", required = false) Boolean update) {

        if (update == null) {
            update = Math.random() > 0.5;
        }

        System.out.println("== jvm_cache_test controller: " + key + " -- update: " + update);

        List<Config> configList = null;
        if (update) {
            configList = configService.listRankCacheUpdate(key);
        } else {
            configList = configService.listRankByCache(key);
        }
        System.out.println(" ");

        return new Gson().toJson(configList);
    }

    @GetMapping(value = "/cache_debug")
    public String cache_debug() {

        Map<String, Object> caches = new HashMap<>();

        concurrentMapCacheManager.getCacheNames().stream().forEach((cacheName) ->
                caches.put(cacheName, concurrentMapCacheManager.getCache(cacheName).getNativeCache()));

        return new Gson().toJson(caches);
    }
}
